package cn.wqb.bpp.common.utils;

import org.springframework.context.ApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import java.util.Map;
import java.util.concurrent.TimeUnit;

public class RedisUtils {

    public static RedisTemplate redisTemplate;

    /**
     * 由于本工具类通常放在外部工具包，无法自动获取RedisTemplate的Bean，所以需要主体程序调用来赋值
     *
     * @param applicationContext
     */
    public static void setRedisTemplate(ApplicationContext applicationContext) {
        Map<String, RedisTemplate> templates = applicationContext.getBeansOfType(RedisTemplate.class);
        for (String key : templates.keySet()) {
            RedisTemplate template = templates.get(key);
            if("RedisTemplate".equals(template.getClass().getSimpleName())){
                redisTemplate = template;
                break;
            }
        }
    }

    public static void setValue(String key, Object value, long timeOutSeconds) {
        ValueOperations<String, Object> vo = redisTemplate.opsForValue();
        vo.set(key, value);
        redisTemplate.expire(key, timeOutSeconds, TimeUnit.SECONDS);
    }

    public static Object getValue(String key) {
        ValueOperations<String, Object> vo = redisTemplate.opsForValue();
        return vo.get(key);
    }
}
